/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ebdesk.view.sppt;
import com.ebdesk.controller.sppt.Print;
import com.ebdesk.controller.sppt.SPPT;
import com.ebdesk.controller.sppt.SPPTTableModel;
import com.ebdesk.view.MainFrame;
import java.awt.Rectangle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.SwingWorker;
/**
 *
 * @author Ikmal Syifai
 */
public class SPPTInternalFrame extends javax.swing.JInternalFrame {
    private Object[][] dataVector;
    private Object[] dataKec;
    private Object[] dataKel;
    private Object[] dataBuku;
    private Object[] dataPrinter;
    
    private String[] header = new String[11];
    private String[] dataDetail = new String[29];
    
    private int firstRecord = 0;
    private int totalRow = 0;
    private boolean clickedSearch = false;
    private Pattern p = Pattern.compile("\\d+");
    
    private SPPT sppt = new SPPT();
    private DetailSPPTDialog dsppt; 
    private MainFrame mf;
    private PrintSettingDialog ps;
    
    StringBuilder cb = new StringBuilder();
    StringBuilder cb2 = new StringBuilder();   
    
    public SPPTInternalFrame(MainFrame mainFrame){
        try{                    
            header[0] = "Pilih";
            header[1] = "NOP";
            header[2] = "Nama Wajib Pajak";
            header[3] = "Alamat Wajib Pajak";
            header[4] = "Tgl Terbit";
            header[5] = "Tgl Cetak";
            header[6] = "Tgl Jatuh Tempo";
            header[7] = "Luas Bumi";
            header[8] = "Luas Bangunan";
            header[9] = "Pajak Terhutang";
            header[10] = "Print";        
            
            cb.setLength(0);
            cb2.setLength(0);        
            
            cb.append("select count(*) from pbb.view_sppt ");
            cb2.append("select * from pbb.view_sppt "
                    + "order by pbb.view_sppt.nop " 
                    + "limit (select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging')::integer");

            totalRow = Integer.parseInt(sppt.getQuery(cb.toString()).toString());
            
            dataKec = sppt.getDataCB(1);
            dataBuku = sppt.getDataCB(3);
            dataPrinter = sppt.getPrinter();
            dsppt = new DetailSPPTDialog(mf, true);
            ps = new PrintSettingDialog(mf, true);
            
            initComponents();
        }
        catch(Exception e){
            e.printStackTrace();
        }    
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tab = new javax.swing.JTable(new SPPTTableModel(dataVector, header));
        jToolBar1 = new javax.swing.JToolBar();
        bFirstBlock = new javax.swing.JButton();
        bPrevBlock = new javax.swing.JButton();
        bPrevRow = new javax.swing.JButton();
        bNextRow = new javax.swing.JButton();
        bNextBlock = new javax.swing.JButton();
        bLastBlock = new javax.swing.JButton();
        cPrinter = new javax.swing.JComboBox();
        cModePrint = new javax.swing.JComboBox();
        bPrint = new javax.swing.JButton();
        bPrintSetting = new javax.swing.JButton();
        checkAll = new javax.swing.JCheckBox();
        pbPrint = new javax.swing.JProgressBar();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cKec = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        cKel = new javax.swing.JComboBox();
        nama = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        nop = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        blok = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        urutdari = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        urutsampai = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        buku = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        tahun = new javax.swing.JTextField();
        bSearch = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        lSelectedRow = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        lSelectedPage = new javax.swing.JLabel();

        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("SPPT");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        tab.setModel(new SPPTTableModel(new Object [][] {
            {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}

        }, header));
        tab.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tab);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        bFirstBlock.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/first.png"))); // NOI18N
        bFirstBlock.setEnabled(false);
        bFirstBlock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bFirstBlockMouseClicked(evt);
            }
        });
        jToolBar1.add(bFirstBlock);

        bPrevBlock.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/rewind.png"))); // NOI18N
        bPrevBlock.setEnabled(false);
        bPrevBlock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bPrevBlockMouseClicked(evt);
            }
        });
        jToolBar1.add(bPrevBlock);

        bPrevRow.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/left.png"))); // NOI18N
        bPrevRow.setEnabled(false);
        bPrevRow.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bPrevRowMouseClicked(evt);
            }
        });
        jToolBar1.add(bPrevRow);

        bNextRow.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/right.png"))); // NOI18N
        bNextRow.setEnabled(false);
        bNextRow.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bNextRowMouseClicked(evt);
            }
        });
        jToolBar1.add(bNextRow);

        bNextBlock.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/forward.png"))); // NOI18N
        bNextBlock.setEnabled(false);
        bNextBlock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bNextBlockMouseClicked(evt);
            }
        });
        jToolBar1.add(bNextBlock);

        bLastBlock.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/last.png"))); // NOI18N
        bLastBlock.setEnabled(false);
        bLastBlock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bLastBlockMouseClicked(evt);
            }
        });
        jToolBar1.add(bLastBlock);

        cPrinter.setModel(new javax.swing.DefaultComboBoxModel(dataPrinter));
        cPrinter.setMaximumSize(new java.awt.Dimension(200, 20));
        cPrinter.setMinimumSize(new java.awt.Dimension(150, 25));
        cPrinter.setPreferredSize(new java.awt.Dimension(150, 15));
        jToolBar1.add(cPrinter);

        cModePrint.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mulai dari kiri", "Mulai dari kanan", "Kiri semua", "Kanan semua" }));
        cModePrint.setMaximumSize(new java.awt.Dimension(200, 20));
        cModePrint.setMinimumSize(new java.awt.Dimension(150, 25));
        cModePrint.setPreferredSize(new java.awt.Dimension(150, 15));
        cModePrint.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cModePrintItemStateChanged(evt);
            }
        });
        jToolBar1.add(cModePrint);

        bPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/print.gif"))); // NOI18N
        bPrint.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        bPrint.setEnabled(false);
        bPrint.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bPrintMouseClicked(evt);
            }
        });
        jToolBar1.add(bPrint);

        bPrintSetting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/script_edit.png"))); // NOI18N
        bPrintSetting.setFocusable(false);
        bPrintSetting.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bPrintSetting.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bPrintSetting.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bPrintSettingMouseClicked(evt);
            }
        });
        jToolBar1.add(bPrintSetting);

        checkAll.setFocusable(false);
        checkAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        checkAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        checkAll.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                checkAllItemStateChanged(evt);
            }
        });
        jToolBar1.add(checkAll);

        pbPrint.setMaximumSize(new java.awt.Dimension(200, 20));
        pbPrint.setMinimumSize(new java.awt.Dimension(150, 25));
        pbPrint.setPreferredSize(new java.awt.Dimension(150, 15));
        pbPrint.setStringPainted(true);
        jToolBar1.add(pbPrint);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Searching", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 0, 255)));

        jLabel1.setText("Kecamatan:");

        cKec.setModel(new javax.swing.DefaultComboBoxModel(dataKec));
        cKec.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cKecItemStateChanged(evt);
            }
        });

        jLabel2.setText("Kelurahan:");

        cKel.setModel(new javax.swing.DefaultComboBoxModel(new String[] {""}));
        cKel.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cKelItemStateChanged(evt);
            }
        });

        nama.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                namaKeyPressed(evt);
            }
        });

        jLabel4.setText("Nama:");

        nop.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nopKeyPressed(evt);
            }
        });

        jLabel3.setText("NOP:");

        jLabel5.setText("Blok:");

        blok.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                blokKeyPressed(evt);
            }
        });

        jLabel6.setText("No. Urut:");

        urutdari.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                urutdariKeyPressed(evt);
            }
        });

        jLabel7.setText("s/d");

        urutsampai.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                urutsampaiKeyPressed(evt);
            }
        });

        jLabel8.setText("Buku:");

        buku.setModel(new javax.swing.DefaultComboBoxModel(dataBuku));
        buku.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                bukuItemStateChanged(evt);
            }
        });

        jLabel9.setText("Tahun");

        tahun.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tahunKeyPressed(evt);
            }
        });

        bSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ebdesk/view/images/search.gif"))); // NOI18N
        bSearch.setEnabled(false);
        bSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bSearchMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cKec, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cKel, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nop, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nama, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(blok, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(urutdari, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(urutsampai, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tahun, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buku, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bSearch)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bSearch)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(cKec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(cKel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(nop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(nama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(blok, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6)
                        .addComponent(urutdari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7)
                        .addComponent(urutsampai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel9)
                        .addComponent(tahun, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(buku, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel8)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        lSelectedRow.setText("asdfasdf");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lSelectedRow, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(lSelectedRow)
                .addGap(0, 3, Short.MAX_VALUE))
        );

        try{
            tab.getSelectionModel().setSelectionInterval(0, 0);

            pbPrint.setVisible(false);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        lSelectedPage.setText("jkjljkj");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lSelectedPage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(lSelectedPage)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        double Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
        lSelectedRow.setText("Row: "+(firstRecord+tab.getSelectedRow()+1)+" of "+sppt.getQuery("select count(*) from pbb.view_sppt").toString());
        lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 715, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void showPB(JProgressBar pb){       
        pb.setValue(0);
        pb.setVisible(true); 
        pb.setIndeterminate(true);
        pb.setStringPainted(false);        
    }
    
    public void hidePB(JProgressBar pb){
        pb.setIndeterminate(false);            
        pb.setStringPainted(true);
        pb.setVisible(false);                     
    }
    
    public void buildQuery(){        
        String Kel = null;
        if(cKel.getSelectedIndex()!=-1){
            Kel = cKel.getSelectedItem().toString();
        }        

        if(Kel == null || Kel.trim().equals("") || Kel.trim().substring(6).equals("-")){
            JOptionPane.showMessageDialog(rootPane, "Ubah Kelurahan sebelum memulai pencarian!!!", "Warning", JOptionPane.WARNING_MESSAGE);
            clickedSearch = false;
            Thread.currentThread().interrupt();
//            return;
        }

        /*
         * Ekstrak no buku
         */
        String snobuku = null;
        int nobuku = 0;
        if(buku.getSelectedIndex()!=-1) snobuku = buku.getSelectedItem().toString();
        
        if(snobuku != null){            
            Matcher m = p.matcher(snobuku);
            while(m.find()) nobuku = Integer.parseInt(m.group());            
        }

        /*
         * Inisialisasi String Builder
         */
        cb.setLength(0);
        cb2.setLength(0);
        
        cb.append("select count(*) from pbb.view_sppt");
        cb2.append("select * from pbb.view_sppt");
        
        /*
         * Inisialisasi penampung cKec
         */
        String Kec = null;

        if(cKec.getSelectedIndex()!=-1){
            Kec = cKec.getSelectedItem().toString();
        }                        
        
        /*
         * Cek isi tiap field
         */
        if(Kec != null ||
        !nop.getText().trim().equals("") ||
        !nama.getText().toUpperCase().trim().equals("") ||
        !blok.getText().trim().equals("") ||
        (!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")) ||
        !tahun.getText().trim().equals("") ||                
        nobuku!=0){
            cb.append(" where");
            cb2.append(" where");
        }
        
        //Kecamatan
        if(Kec != null){
            cb.append(" substring (pbb.view_sppt.nop from 1 for 10) = " 
                    + "(select pbb.pbb_master_kelurahan.kode_kelurahan " 
                    + "from pbb.pbb_master_kelurahan " 
                    + "where " 
                        + "(substring(pbb.pbb_master_kelurahan.kode_kelurahan from 1 for 7) " 
                        + "= (select pbb.pbb_master_kecamatan.kode_kecamatan from pbb.pbb_master_kecamatan where " 
                            + "(substring(pbb.pbb_master_kecamatan.kode_kecamatan from 1 for 4) = (select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'kode_kota') " 
                            + "and pbb.pbb_master_kecamatan.nama_kecamatan = '").append(Kec.trim().substring(6)).append("')) " 
                    + "and pbb.pbb_master_kelurahan.nama_kelurahan = '").append(Kel.trim().substring(6)).append("'))");
            
            cb2.append(" substring (pbb.view_sppt.nop from 1 for 10) = " 
                    + "(select pbb.pbb_master_kelurahan.kode_kelurahan " 
                    + "from pbb.pbb_master_kelurahan " 
                    + "where " 
                        + "(substring(pbb.pbb_master_kelurahan.kode_kelurahan from 1 for 7) " 
                        + "= (select pbb.pbb_master_kecamatan.kode_kecamatan from pbb.pbb_master_kecamatan where " 
                            + "(substring(pbb.pbb_master_kecamatan.kode_kecamatan from 1 for 4) = (select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'kode_kota') " 
                            + "and pbb.pbb_master_kecamatan.nama_kecamatan = '").append(Kec.trim().substring(6)).append("')) " 
                    + "and pbb.pbb_master_kelurahan.nama_kelurahan = '").append(Kel.trim().substring(6)).append("'))");
            
            if(!nop.getText().trim().equals("") ||
            !nama.getText().toUpperCase().trim().equals("") ||
            !blok.getText().trim().equals("") ||
            (!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")) ||
            !tahun.getText().trim().equals("") ||    
            nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }            
        }                                
        
        //NOP
        if(!nop.getText().trim().equals("")){
            cb.append(" nop = '").append(nop.getText().trim()).append("'");
            cb2.append(" nop = '").append(nop.getText().trim()).append("'");
            
            if(!nama.getText().toUpperCase().trim().equals("") ||
            !blok.getText().trim().equals("") ||
            (!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")) ||    
            !tahun.getText().trim().equals("") ||                        
            nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }
        }                
        
        //Nama
        if(!nama.getText().toUpperCase().trim().equals("")){
            cb.append(" wp_nama like '%").append(nama.getText().toUpperCase().trim()).append("%'");
            cb2.append(" wp_nama like '%").append(nama.getText().toUpperCase().trim()).append("%'");
            
            if(!blok.getText().trim().equals("") ||
            (!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")) ||
            !tahun.getText().trim().equals("") ||                        
            nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }            
        }        
        
        //Blok
        if(!blok.getText().trim().equals("")){
            cb.append(" substr(nop,11,3) = '").append(blok.getText().trim()).append("'");
            cb2.append(" substr(nop,11,3) = '").append(blok.getText().trim()).append("'");
            
            if((!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")) ||
            !tahun.getText().trim().equals("") ||                        
            nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }
        }
              
        //No Urut
        if(!urutdari.getText().trim().equals("") && !urutsampai.getText().trim().equals("")){
            cb.append(" cast(substr(nop,14,4) as integer) between ").append(urutdari.getText().trim()).append(" and ").append(urutsampai.getText().trim());
            cb2.append(" cast(substr(nop,14,4) as integer) between ").append(urutdari.getText().trim()).append(" and ").append(urutsampai.getText().trim());
            
            if(!tahun.getText().trim().equals("") ||    
            nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }
        }
        
        //Tahun
        if(!tahun.getText().trim().equals("")){
            cb.append(" sppt_tahun_pajak = '").append(tahun.getText().trim()).append("'");
            cb2.append(" sppt_tahun_pajak = '").append(tahun.getText().trim()).append("'");
            
            if(nobuku!=0){
                cb.append(" and");
                cb2.append(" and");
            }
        }
        
        //Buku
        if(nobuku!=0){
            cb.append(" buku = ").append(nobuku);
            cb2.append(" buku = ").append(nobuku);
        }                                      
    }
    
    private void blokKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_blokKeyPressed
        //Hanya menerima 0-9, backspace, dan delete
        if ((evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9') || evt.getKeyCode() == 8 || evt.getKeyCode() == 127) {
            blok.setEditable(true);
            clickedSearch = false;
        } else {
            blok.setEditable(false);
        }
    }//GEN-LAST:event_blokKeyPressed

    private void cKecItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cKecItemStateChanged
        // TODO add your handling code here:
        try {
            dataKel = sppt.getDataCB(2, evt.getItem().toString().substring(6));
            cKel.setModel(new javax.swing.DefaultComboBoxModel(dataKel));
            clickedSearch = false;
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }//GEN-LAST:event_cKecItemStateChanged

    private void cKelItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cKelItemStateChanged
        clickedSearch = false;
    }//GEN-LAST:event_cKelItemStateChanged

    private void nopKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nopKeyPressed
        int input = evt.getKeyChar();
        int inputBspace = evt.getKeyCode();
        if ((input >= '0' && input <= '9') || (inputBspace == evt.VK_BACK_SPACE) || (inputBspace == evt.VK_DELETE)||(inputBspace == evt.VK_LEFT) || (inputBspace == evt.VK_RIGHT)) {
            nop.setEditable(true);
            clickedSearch = false;
        } else {
            nop.setEditable(false);
        }
    }//GEN-LAST:event_nopKeyPressed

    private void namaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_namaKeyPressed
        int input = evt.getKeyChar();
        int inputBspace = evt.getKeyCode();
        if ((input >= 'A' && input <= 'Z') || (input >= 'a' && input <= 'z') || (inputBspace == evt.VK_BACK_SPACE) || (inputBspace == evt.VK_DELETE) || (inputBspace == evt.VK_SPACE)||(inputBspace == evt.VK_LEFT) || (inputBspace == evt.VK_RIGHT)) {            nama.setEditable(true);
            clickedSearch = false;
        } else {
            nama.setEditable(false);
        }
    }//GEN-LAST:event_namaKeyPressed

    private void urutdariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_urutdariKeyPressed
        int input = evt.getKeyChar();
        int inputBspace = evt.getKeyCode();
        if ((input >= '0' && input <= '9') || (inputBspace == evt.VK_BACK_SPACE) || (inputBspace == evt.VK_DELETE)||(inputBspace == evt.VK_LEFT) || (inputBspace == evt.VK_RIGHT)) {
            urutdari.setEditable(true);
            clickedSearch = false;
        } else {
            urutdari.setEditable(false);
        }
    }//GEN-LAST:event_urutdariKeyPressed

    private void urutsampaiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_urutsampaiKeyPressed
        int input = evt.getKeyChar();
        int inputBspace = evt.getKeyCode();
        if ((input >= '0' && input <= '9') || (inputBspace == evt.VK_BACK_SPACE) || (inputBspace == evt.VK_DELETE)||(inputBspace == evt.VK_LEFT) || (inputBspace == evt.VK_RIGHT)) {            urutsampai.setEditable(true);
            clickedSearch = false;
        } else {
            urutsampai.setEditable(false);
        }
    }//GEN-LAST:event_urutsampaiKeyPressed

    private void bukuItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_bukuItemStateChanged
        clickedSearch = false;
    }//GEN-LAST:event_bukuItemStateChanged

    private void tahunKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tahunKeyPressed
        int input = evt.getKeyChar();
        int inputBspace = evt.getKeyCode();
        if ((input >= '0' && input <= '9') || (inputBspace == evt.VK_BACK_SPACE) || (inputBspace == evt.VK_DELETE)||(inputBspace == evt.VK_LEFT) || (inputBspace == evt.VK_RIGHT)) {
            tahun.setEditable(true);
            clickedSearch = false;
        } else {
            tahun.setEditable(false);
        }
    }//GEN-LAST:event_tahunKeyPressed

    private void bSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bSearchMouseClicked
        if (!bSearch.isEnabled()) {
            System.out.println("keluar");
            return;
        }

        bSearch.setEnabled(false);
        bFirstBlock.setEnabled(false);
        bLastBlock.setEnabled(false);
        bNextBlock.setEnabled(false);
        bPrevBlock.setEnabled(false);
        bNextRow.setEnabled(false);
        bPrevRow.setEnabled(false);

        SwingWorker search = new SwingWorker<Object[][], Void>() {

            boolean marker = false;

            @Override
            public Object[][] doInBackground() {
                try {
                    buildQuery();
                    if (Thread.currentThread().isInterrupted()) {
                        throw new InterruptedException();
                    }

                    //Set total row
                    totalRow = Integer.parseInt(sppt.getQuery(cb.toString()).toString());

                    //Set data yang ditampilkan
                    int Block = Integer.parseInt(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
                    cb2.append(" order by nop ").append(" limit ").append(Block);

                    System.out.println(cb2.toString());
                    dataVector = sppt.getData(cb2.toString());
                    return dataVector;
                } catch (InterruptedException e) {
                    marker = true;
                    return dataVector;
                }
            }

            @Override
            public void done() {
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                    tab.getSelectionModel().setSelectionInterval(0, 0);
                    firstRecord = 0;

                    if (totalRow != 0) {
                        double Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());                      
                        lSelectedRow.setText("Row: "+(firstRecord+tab.getSelectedRow()+1)+" of "+ totalRow);
                        lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));
                    } else {
                        lSelectedRow.setText("Row: 0 of 0");
                    }

                    if (!marker) {
                        clickedSearch = true;
                    }

                    checkAll.setSelected(false);

                    hidePB(pbPrint);
                    bSearch.setEnabled(true);
                    bFirstBlock.setEnabled(true);
                    bLastBlock.setEnabled(true);
                    bNextBlock.setEnabled(true);
                    bPrevBlock.setEnabled(true);
                    bNextRow.setEnabled(true);
                    bPrevRow.setEnabled(true);

                    /*
                     * Peringatan filter No Urut jika salah satu field kosong
                     */
                    if (urutdari.getText().trim().equals("") ^ urutsampai.getText().trim().equals("")) {
                        JOptionPane.showMessageDialog(rootPane, "No urut tidak dijadikan filter karena salah satu field kosong!!!", "Warning", JOptionPane.WARNING_MESSAGE);
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        search.execute();

        tab.setModel(new SPPTTableModel(new Object[][]{
                    {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                        "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}
                }, header));

        showPB(pbPrint);
    }//GEN-LAST:event_bSearchMouseClicked

    private void tabMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabMouseClicked
        // TODO add your handling code here:       
        JTable tab = (JTable) evt.getSource();
        String nop = (String) tab.getModel().getValueAt(tab.getSelectedRow(), 1);
        Matcher m = p.matcher(nop);
        StringBuilder sb = new StringBuilder();
        String printer = "";

        while (m.find()) {
            sb.append(m.group());
        }

        if (cPrinter.getSelectedIndex() != -1) {
            printer = cPrinter.getSelectedItem().toString();
        }

        if (evt.getClickCount() == 2) {
            try {
                dataDetail = sppt.getDetailData("select * from pbb.view_sppt where nop='" + sb.toString() + "'");
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
            
            dsppt.setLocationRelativeTo(null);
            dsppt.SetTextFields(dataDetail);
            dsppt.setPrinter(printer);
            dsppt.setVisible(true);
        }

        if (evt.getClickCount() == 1) {
            if (tab.getSelectedColumn() == 10) {
                if (printer.equals("")) {
                    JOptionPane.showMessageDialog(rootPane, "Pilih printer lebih dulu!!!", "Warning", JOptionPane.WARNING_MESSAGE);
                } else {
                    int confirm = JOptionPane.showOptionDialog(rootPane, "Apakah Anda yakin akan print data?", "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == 0) {//OK pressed
                        Print p = new Print(cPrinter.getSelectedItem().toString());
                        try {
                            String data[][] = new String[dataVector.length][38];
                            data = sppt.getPrintData("select a.*, "
                                        + "coalesce(b.luas_bumi_beban_sppt, 0::numeric) as luas_bumi_beban_sppt, "
                                        + "coalesce(b.luas_bng_beban_sppt, 0::numeric) as luas_bng_beban_sppt, "
                                        + "coalesce(b.kd_kls_tanah, '0'::character) as kd_kls_tanah, "
                                        + "coalesce(b.kd_kls_bng, '0'::character) as kd_kls_bng, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_tanah where kd_kls_tanah = kode), 0::double precision) as nilai_per_m2_tanah2, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_bangunan where kd_kls_bng = kode), 0::double precision) as nilai_per_m2_bangunan2, "
                                        + "coalesce(b.njop_bumi_beban_sppt, 0::numeric) as njop_bumi_beban_sppt, "
                                        + "coalesce(b.njop_bng_beban_sppt, 0::numeric) as njop_bng_beban_sppt "
                                        + "from (select * from pbb.view_sppt where nop='" + sb.toString() + "') as a "
                                        + "left outer join pbb.pbb_sppt_op_bersama as b "
                                        + "on a.nop = b.nop and a.sppt_tahun_pajak = b.thn_pajak_sppt");

                            int mode = 0;
                            switch (cModePrint.getSelectedIndex()) {
                                case 0:
                                    mode = 0;
                                    break;
                                case 1:
                                    mode = 1;
                                    break;
                                case 2:
                                    mode = 2;
                                    break;
                                case 3:
                                    mode = 3;
                                    break;
                            }

                            p.doPrint(data, pbPrint, mode);
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.exit(1);
                        }
                    }
                }
            }
        }

        lSelectedRow.setText(lSelectedRow.getText().replaceAll("Row: \\d+ of \\d+", "Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow));
    }//GEN-LAST:event_tabMouseClicked

    private void bFirstBlockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bFirstBlockMouseClicked
        if (!bFirstBlock.isEnabled()) {
            return;
        }

        bSearch.setEnabled(false);
        bFirstBlock.setEnabled(false);
        bLastBlock.setEnabled(false);
        bNextBlock.setEnabled(false);
        bPrevBlock.setEnabled(false);
        bNextRow.setEnabled(false);
        bPrevRow.setEnabled(false);

        SwingWorker block = new SwingWorker<Object[][], Void>() {

            double Block;                      

            @Override
            public Object[][] doInBackground() {
                try {
                    Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());

                    firstRecord = 0;

                    //Sudah pernah di filter
                    if (cb2.toString().contains("limit")) {
                        cb2.replace(cb2.indexOf("limit"), cb2.length(), "limit " + Block + " offset " + firstRecord);
                    } else {
                        cb2.append(" limit ").append(Block);
                    }

                    System.out.println(cb2.toString());
                    dataVector = sppt.getData(cb2.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                return dataVector;
            }

            @Override
            public void done() {
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                } catch (InterruptedException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                tab.getSelectionModel().addSelectionInterval(0, 0);
                lSelectedRow.setText("Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow);
                lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));
                checkAll.setSelected(false);
                hidePB(pbPrint);
                bSearch.setEnabled(true);
                bFirstBlock.setEnabled(true);
                bLastBlock.setEnabled(true);
                bNextBlock.setEnabled(true);
                bPrevBlock.setEnabled(true);
                bNextRow.setEnabled(true);
                bPrevRow.setEnabled(true);
            }
        };

        block.execute();

        tab.setModel(new SPPTTableModel(new Object[][]{
                    {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                        "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}
                }, header));

        showPB(pbPrint);
    }//GEN-LAST:event_bFirstBlockMouseClicked

    private void bPrevBlockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrevBlockMouseClicked
        if (!bPrevBlock.isEnabled()) {
            return;
        }

        bSearch.setEnabled(false);
        bFirstBlock.setEnabled(false);
        bLastBlock.setEnabled(false);
        bNextBlock.setEnabled(false);
        bPrevBlock.setEnabled(false);
        bNextRow.setEnabled(false);
        bPrevRow.setEnabled(false);

        SwingWorker block = new SwingWorker<Object[][], Void>() {

            double Block;

            @Override
            public Object[][] doInBackground() {
                try {
                    Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
                    if ((firstRecord - Block) >= 0) {
                        firstRecord -= Block;

                        //Sudah pernah di filter
                        if (cb2.toString().contains("limit")) {
                            cb2.replace(cb2.indexOf("limit"), cb2.length(), "limit " + Block + " offset " + firstRecord);
                        } else {
                            cb2.append(" limit ").append(Block);
                        }

                        System.out.println(cb2.toString());
                        dataVector = sppt.getData(cb2.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                return dataVector;
            }

            @Override
            public void done() {
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                } catch (InterruptedException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                tab.getSelectionModel().addSelectionInterval(0, 0);
                lSelectedRow.setText("Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow);
                lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));
                checkAll.setSelected(false);
                hidePB(pbPrint);
                bSearch.setEnabled(true);
                bFirstBlock.setEnabled(true);
                bLastBlock.setEnabled(true);
                bNextBlock.setEnabled(true);
                bPrevBlock.setEnabled(true);
                bNextRow.setEnabled(true);
                bPrevRow.setEnabled(true);
            }
        };

        block.execute();

        tab.setModel(new SPPTTableModel(new Object[][]{
                    {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                        "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}
                }, header));

        showPB(pbPrint);
    }//GEN-LAST:event_bPrevBlockMouseClicked

    private void bPrevRowMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrevRowMouseClicked
        if (!bPrevRow.isEnabled()) {
            return;
        }
        int row = tab.getSelectedRow();

        if (row - 1 < 0) {
            row = 0;
            if (firstRecord > 0) {
                this.bPrevBlockMouseClicked(evt);
            }
        } else {
            row--;
        }

        tab.changeSelection(row, 1, false, false);
        tab.getSelectionModel().addSelectionInterval(row, row);
        tab.scrollRectToVisible(new Rectangle(tab.getCellRect(row, 0, true)));
        lSelectedRow.setText(lSelectedRow.getText().replaceAll("Row: \\d+ of \\d+", "Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow));
    }//GEN-LAST:event_bPrevRowMouseClicked

    private void bNextRowMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bNextRowMouseClicked
        if (!bNextRow.isEnabled()) {
            return;
        }

        try {
            int rows = Integer.parseInt(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
            int row = tab.getSelectedRow();
            if (row + 2 > rows) {
                row = rows - 1;
                this.bNextBlockMouseClicked(evt);
            } else {
                if (firstRecord + tab.getSelectedRow() + 1 < totalRow) {
                    row++;
                }
            }

            tab.changeSelection(row, 1, false, false);
            tab.getSelectionModel().addSelectionInterval(row, row);
            tab.scrollRectToVisible(new Rectangle(tab.getCellRect(row, 0, true)));
            lSelectedRow.setText(lSelectedRow.getText().replaceAll("Row: \\d+ of \\d+", "Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow));
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }//GEN-LAST:event_bNextRowMouseClicked

    private void bNextBlockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bNextBlockMouseClicked
        if (!bNextBlock.isEnabled()) {
            return;
        }

        bSearch.setEnabled(false);
        bFirstBlock.setEnabled(false);
        bLastBlock.setEnabled(false);
        bNextBlock.setEnabled(false);
        bPrevBlock.setEnabled(false);
        bNextRow.setEnabled(false);
        bPrevRow.setEnabled(false);

        SwingWorker block = new SwingWorker<Object[][], Void>() {

            double Block;

            @Override
            public Object[][] doInBackground() {
                try {
                    Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
                    if ((firstRecord + Block) < totalRow) {
                        firstRecord += Block;

                        //Sudah pernah di filter
                        if (cb2.toString().contains("limit")) {
                            cb2.replace(cb2.indexOf("limit"), cb2.length(), "limit " + Block + " offset " + firstRecord);
                        } else {
                            cb2.append(" limit ").append(Block);
                        }

                        System.out.println(cb2.toString());
                        dataVector = sppt.getData(cb2.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                return dataVector;
            }

            @Override
            public void done() {
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                } catch (InterruptedException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                tab.getSelectionModel().addSelectionInterval(0, 0);
                lSelectedRow.setText("Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow);
                lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));
                checkAll.setSelected(false);
                hidePB(pbPrint);
                bSearch.setEnabled(true);
                bFirstBlock.setEnabled(true);
                bLastBlock.setEnabled(true);
                bNextBlock.setEnabled(true);
                bPrevBlock.setEnabled(true);
                bNextRow.setEnabled(true);
                bPrevRow.setEnabled(true);
            }
        };

        block.execute();

        tab.setModel(new SPPTTableModel(new Object[][]{
                    {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                        "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}
                }, header));

        showPB(pbPrint);
    }//GEN-LAST:event_bNextBlockMouseClicked

    private void bLastBlockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bLastBlockMouseClicked
        if (!bLastBlock.isEnabled()) {
            return;
        }

        bSearch.setEnabled(false);
        bFirstBlock.setEnabled(false);
        bLastBlock.setEnabled(false);
        bNextBlock.setEnabled(false);
        bPrevBlock.setEnabled(false);
        bNextRow.setEnabled(false);
        bPrevRow.setEnabled(false);

        SwingWorker block = new SwingWorker<Object[][], Void>() {

            double Block;

            @Override
            public Object[][] doInBackground() {
                try {
                    Block = Double.parseDouble(sppt.getQuery("select pbb.pbb_setting.value from pbb.pbb_setting where pbb.pbb_setting.setting = 'paging'").toString());
                    firstRecord = (int)(Block * Math.floor(totalRow / Block));

                    //Sudah pernah di filter
                    if (cb2.toString().contains("limit")) {
                        cb2.replace(cb2.indexOf("limit"), cb2.length(), "limit " + Block + " offset " + firstRecord);
                    } else {
                        cb2.append(" limit ").append(Block);
                    }

                    System.out.println(cb2.toString());
                    dataVector = sppt.getData(cb2.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                return dataVector;
            }

            @Override
            public void done() {
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                } catch (InterruptedException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                tab.getSelectionModel().addSelectionInterval(0, 0);
                lSelectedRow.setText("Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow);
                lSelectedPage.setText("Page: " + (int)(firstRecord / Block + 1) + " of " + (int)Math.ceil(totalRow / Block));
                checkAll.setSelected(false);
                hidePB(pbPrint);
                bSearch.setEnabled(true);
                bFirstBlock.setEnabled(true);
                bLastBlock.setEnabled(true);
                bNextBlock.setEnabled(true);
                bPrevBlock.setEnabled(true);
                bNextRow.setEnabled(true);
                bPrevRow.setEnabled(true);
            }
        };

        block.execute();

        tab.setModel(new SPPTTableModel(new Object[][]{
                    {"Loading..", "Loading..", "Loading..", "Loading..", "Loading..",
                        "Loading..", "Loading..", "Loading..", "Loading..", "Loading..", "Loading.."}
                }, header));

        showPB(pbPrint);
    }//GEN-LAST:event_bLastBlockMouseClicked

    private void cModePrintItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cModePrintItemStateChanged
        dsppt.setMode(cModePrint.getSelectedIndex());
    }//GEN-LAST:event_cModePrintItemStateChanged

    private void bPrintMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrintMouseClicked
        if (!bPrint.isEnabled()) {
            return;
        }        
        
        if (cKel.getSelectedIndex() != -1) {
            if (cKel.getSelectedItem().toString().trim().substring(6).equals("-")) {
                JOptionPane.showMessageDialog(rootPane, "Ubah Kelurahan sebelum memulai pencarian!!!", "Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
        }

        if (cPrinter.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(rootPane, "Pilih printer lebih dulu!!!", "Warning", JOptionPane.WARNING_MESSAGE);
        } else {
            /*
             * Print hanya jika kecamatan, kelurahan, tahun, dan buku sudah
             * dipilih *
             */
            if (cKec.getSelectedIndex() != -1 && cKel.getSelectedIndex() != -1 && !tahun.getText().equals("") && buku.getSelectedIndex() != -1) {
                /*
                 * Print hanya jika user klik tombol Search tepat sebelum klik
                 * tombol Print Dilakukan untuk mencegah user mengubah filter
                 * tanpa klik tombol Search kemudian langsung klik tombol Print
                 */

                if (clickedSearch) {
                    int confirm = JOptionPane.showOptionDialog(rootPane, "Apakah Anda yakin akan print data\nKecamatan: "
                            + cKec.getSelectedItem().toString() + "\nKelurahan: " + cKel.getSelectedItem().toString() + "\nTahun: " + tahun.getText()
                            + "\nMode Print: " + cModePrint.getSelectedItem().toString(), "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

                    if (confirm == 0) {//OK pressed                     
                        try {
                            String data[][];
                            StringBuilder query2 = new StringBuilder();
                            StringBuilder sbnop = new StringBuilder();
                            boolean flag = false;

                            query2.append("select * from pbb.view_spptMARK");

                            for (int i = 0; i < dataVector.length; i++) {
                                if (tab.getModel().getValueAt(i, 0) == Boolean.TRUE) {//cek apakah checked                
                                    String nop = tab.getModel().getValueAt(i, 1).toString();
                                    Matcher m = p.matcher(nop);
                                    sbnop.setLength(0);

                                    while (m.find()) {
                                        sbnop.append(m.group());
                                    }

                                    if (query2.substring(27).equals("MARK")) {//belum ada 'where' dalam query
                                        query2.replace(27, query2.length(), "");
                                        query2.append(" where nop = '").append(sbnop).append("'");
                                    } else {
                                        query2.append(" or nop = '").append(sbnop).append("'");
                                    }

                                    flag = flag || true;
                                } else {//sebelum print semua record, pastikan semua unchecked              
                                    flag = flag || false;
                                }
                            }

                            if (!flag) {//jika semua unchecked, print data terfilter
                                StringBuilder temp = new StringBuilder();
                                temp.append("select a.*, "
                                        + "coalesce(b.luas_bumi_beban_sppt, 0::numeric) as luas_bumi_beban_sppt, "
                                        + "coalesce(b.luas_bng_beban_sppt, 0::numeric) as luas_bng_beban_sppt, "
                                        + "coalesce(b.kd_kls_tanah, '0'::character) as kd_kls_tanah, "
                                        + "coalesce(b.kd_kls_bng, '0'::character) as kd_kls_bng, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_tanah where kd_kls_tanah = kode), 0::double precision) as nilai_per_m2_tanah2, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_bangunan where kd_kls_bng = kode), 0::double precision) as nilai_per_m2_bangunan2, "
                                        + "coalesce(b.njop_bumi_beban_sppt, 0::numeric) as njop_bumi_beban_sppt, "
                                        + "coalesce(b.njop_bng_beban_sppt, 0::numeric) as njop_bng_beban_sppt "
                                        + "from (");
                                temp.append(cb2.toString());
                                temp.append(") as a "
                                        + "left outer join pbb.pbb_sppt_op_bersama as b "
                                        + "on a.nop = b.nop and a.sppt_tahun_pajak = b.thn_pajak_sppt");
                                data = sppt.getPrintData(temp.toString());
                                System.out.println("printquery: " + temp.toString());
                            } else {
                                query2.append("order by nop");

                                StringBuilder temp = new StringBuilder();
                                temp.append("select a.*, "
                                        + "coalesce(b.luas_bumi_beban_sppt, 0::numeric) as luas_bumi_beban_sppt, "
                                        + "coalesce(b.luas_bng_beban_sppt, 0::numeric) as luas_bng_beban_sppt, "
                                        + "coalesce(b.kd_kls_tanah, '0'::character) as kd_kls_tanah, "
                                        + "coalesce(b.kd_kls_bng, '0'::character) as kd_kls_bng, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_tanah where kd_kls_tanah = kode), 0::double precision) as nilai_per_m2_tanah2, "
                                        + "coalesce((select nilai_per_m2 from pbb.pbb_kelas_bangunan where kd_kls_bng = kode), 0::double precision) as nilai_per_m2_bangunan2, "
                                        + "coalesce(b.njop_bumi_beban_sppt, 0::numeric) as njop_bumi_beban_sppt, "
                                        + "coalesce(b.njop_bng_beban_sppt, 0::numeric) as njop_bng_beban_sppt "
                                        + "from (");
                                temp.append(query2.toString());
                                temp.append(") as a "
                                        + "left outer join pbb.pbb_sppt_op_bersama as b "
                                        + "on a.nop = b.nop and a.sppt_tahun_pajak = b.thn_pajak_sppt");
                                data = sppt.getPrintData(temp.toString());
                                System.out.println("printquery: " + temp.toString());
                            }

                            if (!cPrinter.getSelectedItem().toString().equals("")) {
                                Print p = new Print(cPrinter.getSelectedItem().toString());

                                int mode = 0;
                                switch (cModePrint.getSelectedIndex()) {
                                    case 0:
                                        mode = 0;
                                        break;
                                    case 1:
                                        mode = 1;
                                        break;
                                    case 2:
                                        mode = 2;
                                        break;
                                    case 3:
                                        mode = 3;
                                        break;
                                }
                                p.doPrint(data, pbPrint, mode);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.exit(1);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Klik tombol Search lebih dulu!!!", "Warning", JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(rootPane, "Pilih Kecamatan, Kelurahan, Tahun, dan Buku lebih dulu!!!", "Warning", JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_bPrintMouseClicked

    private void bPrintSettingMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrintSettingMouseClicked
        ps.setResizable(false);
        ps.setLocationRelativeTo(null);
        ps.setVisible(true);
    }//GEN-LAST:event_bPrintSettingMouseClicked

    private void checkAllItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_checkAllItemStateChanged
        if (dataVector == null) {
            return;
        }

        //Select All
        if (checkAll.isSelected()) {
            for (int i = 0; i < dataVector.length; i++) {
                dataVector[i][0] = Boolean.TRUE;
            }
        } else {
            for (int i = 0; i < dataVector.length; i++) {
                dataVector[i][0] = Boolean.FALSE;
            }
        }

        tab.setModel(new SPPTTableModel(dataVector, header));
        tab.getSelectionModel().addSelectionInterval(0, 0);
        lSelectedRow.setText("Row: " + (firstRecord + tab.getSelectedRow() + 1) + " of " + totalRow);
    }//GEN-LAST:event_checkAllItemStateChanged

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        // TODO add your handling code here:
        bSearch.setEnabled(false);
        
        SwingWorker tableinit = new SwingWorker<Object[][], Void>(){
            @Override
            public Object[][] doInBackground(){
                try {                        
                    dataVector = sppt.getData(cb2.toString());                        
                } catch (Exception ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                return dataVector;
            }

            @Override
            public void done(){
                try {
                    tab.setModel(new SPPTTableModel(get(), header));
                    hidePB(pbPrint);
                    bSearch.setEnabled(true);   
                    bFirstBlock.setEnabled(true);
                    bLastBlock.setEnabled(true);
                    bNextBlock.setEnabled(true);
                    bPrevBlock.setEnabled(true);
                    bNextRow.setEnabled(true);
                    bPrevRow.setEnabled(true);
                    bPrint.setEnabled(true);                
                } catch (InterruptedException ex) {                
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(SPPTInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        tableinit.execute();
        showPB(pbPrint);                                  
    }//GEN-LAST:event_formInternalFrameOpened
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bFirstBlock;
    private javax.swing.JButton bLastBlock;
    private javax.swing.JButton bNextBlock;
    private javax.swing.JButton bNextRow;
    private javax.swing.JButton bPrevBlock;
    private javax.swing.JButton bPrevRow;
    private javax.swing.JButton bPrint;
    private javax.swing.JButton bPrintSetting;
    private javax.swing.JButton bSearch;
    private javax.swing.JTextField blok;
    private javax.swing.JComboBox buku;
    private javax.swing.JComboBox cKec;
    private javax.swing.JComboBox cKel;
    private javax.swing.JComboBox cModePrint;
    private javax.swing.JComboBox cPrinter;
    private javax.swing.JCheckBox checkAll;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lSelectedPage;
    private javax.swing.JLabel lSelectedRow;
    private javax.swing.JTextField nama;
    private javax.swing.JTextField nop;
    private javax.swing.JProgressBar pbPrint;
    private javax.swing.JTable tab;
    private javax.swing.JTextField tahun;
    private javax.swing.JTextField urutdari;
    private javax.swing.JTextField urutsampai;
    // End of variables declaration//GEN-END:variables
}
